package com.team.teamuserservice.websocket.service;

import com.team.teamuserservice.Exception.CancelErrorException;
import com.team.teamuserservice.annotation.WebsocketMessageType;
import com.team.teamuserservice.entity.dto.WebsocketMessage;
import com.team.teamuserservice.entity.po.BizRescueTask;
import com.team.teamuserservice.service.IBizRescueTaskService;
import com.team.teamuserservice.uitls.MessageType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;

@Component
@WebsocketMessageType(MessageType.CANCEL)
public class CancelMessageHandler implements MessageHandler{

    @Autowired
    private IBizRescueTaskService bizRescueTaskService;



    @Override
    public void handleMessage(WebSocketSession session, WebsocketMessage message) throws IOException {
        //这个操作是前端商家点击取消接单了 , 这个时候WebsocketMessage中的message就是用户id
        Long userId = (Long) message.getMessage();

        //先修改订单状态 , 这个时候订单的状态一定要是接单中 , 如果不是接单中就直接返回自定义异常TODO
        boolean success = bizRescueTaskService.lambdaUpdate()
                .eq(BizRescueTask::getUserId, userId)
                .eq(BizRescueTask::getStatus, "1")
                .set(BizRescueTask::getStatus, "3")
                .update();
        if (!success) {
            //修改失败 , 抛出异常 , 这意味只有一种可能 , 就是用户取消了订单 , 接收到了这个异常 , 前端直接设置为取消这个救援就可以
            throw new CancelErrorException("肯定是有人取消订单过了");
        }

        //修改成功了 . 要通知用户
        session.sendMessage(new TextMessage("你自生自灭吧 , 商家取消了"));

    }
}
